package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.es.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dtos.UserSearchDto;
import com.heima.search.service.IHistoryService;
import com.heima.search.service.IUserSearchService;
import com.heima.utils.threadlocal.ApThreadLocal;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserSearchServiceImpl implements IUserSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private IHistoryService historyService;
    /**
     * 搜索业务
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        //2.创建搜索请求对象
        SearchRequest searchRequest=new SearchRequest("app_info_article");

        //建议对关键字进行空格处理， trim()只能去除收尾空格，中间的空格，replace()替换
        dto.setSearchWords(dto.getSearchWords().trim());


        //2.5 异步调用保存历史记录
        ApUser apUser = ApThreadLocal.getApUser();
        if(apUser!=null){
            Integer userId = apUser.getId();
            historyService.saveHistoryToMongo(dto.getSearchWords(),userId.longValue());
        }




        //3.执行DSL语句
            //执行复合查询，bool查询  all
        BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
        if(dto.getSearchWords()==null){
            //查询所有
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }else{
            boolQueryBuilder.must(QueryBuilders.matchQuery("all",dto.getSearchWords()));
        }
        //最小时间
        if(dto.getMinBehotTime()!=null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        }

        searchRequest.source().query(boolQueryBuilder);

        //分页
        searchRequest.source().from(0).size(dto.getPageSize());
        //排序
        searchRequest.source().sort("publishTime", SortOrder.DESC);
        //高亮
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.requireFieldMatch(false);

        searchRequest.source().highlighter(highlightBuilder);

        //1.执行搜索
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);


        //封装一个List集合来承载取出来的数据
        List list=new ArrayList<>();


        //4.结果封装
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            //4.1 获取source
            Map<String, Object> map = hit.getSourceAsMap();

            //4.3 取出高亮域
            HighlightField highlightField = hit.getHighlightFields().get("title");
            if(highlightField.getFragments().length>0){
                String hightTitel = highlightField.getFragments()[0].toString();
                map.put("h_title",hightTitel);
            }else{
                map.put("h_title",map.get("title"));
            }

            list.add(map);
        }

        return ResponseResult.okResult(list);
    }

    /**
     * 同步数据
     *
     * @param message
     */
    @Override
    public void syncES(String message) {

        //1.转化格式
        SearchArticleVo articleVo = JSON.parseObject(message, SearchArticleVo.class);

        IndexRequest indexRequest=new IndexRequest("app_info_article").id(articleVo.getId()+"");
        indexRequest.source(message, XContentType.JSON);
        try {
            client.index(indexRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
